#!/usr/bin/python3
# -*- coding: utf-8 -*-


from flask import Flask,jsonify,request,abort

from conf.config import CONF
from contro.function import *
from contro.log import *
import sys


Error_message={"Error":"Please use the correct JSON"}


app = Flask(__name__)


@app.route('/sw/test',methods=['POST'])
def sw_post():
    if not request.json:
        logging.error("JSON is not uploaded or the JSON format is incorrect")
        abort(400)
    #fio
    elif 'storage' in request.json:
        logging.info("start storage test")
        FIO_OPTS = request.json['storage']
        # check json
        if not 'name' in FIO_OPTS or not 'type' in FIO_OPTS or not 'filename' in FIO_OPTS or not 'bs' in FIO_OPTS or not 'host' in FIO_OPTS:
            logging.error(Error_message, request.json)
            return jsonify(Error_message)
        # run fio test
        logging.info("Start testing with FIO")
        name = FIO_OPTS['name']
        type = FIO_OPTS['type']
        filename = FIO_OPTS['filename']
        bs = FIO_OPTS['bs']
        host = FIO_OPTS['host'],
        json = FIO_TEST(name, type, filename, bs, host)
        # add tag
        json['name'] = name
        json['test_type'] = "storage"
        logging.debug("return fio test json:" + str(json))
        return jsonify(json)
    #qos
    elif 'qos' in request.json:
        logging.info("start qos test")
        QOS_OPTS = request.json['qos']
        # check json
        if not 'name' in QOS_OPTS or not 'server' in QOS_OPTS or not 'client' in QOS_OPTS:
            print(Error_message, request.json)
            return jsonify(Error_message)
        # run qos test
        name=QOS_OPTS['name']
        server=QOS_OPTS['server']
        client=QOS_OPTS['client']
        json=QOS_TEST(name, server, client)
        logging.debug("return qos test json:" + str(json))
        return jsonify(json)
    else:
        print(Error_message, request.json)
        return jsonify(Error_message)


if __name__ == '__main__':
    apiip = CONF.API.BindHost
    apiprot = CONF.API.BindPort
    app.run(host=apiip,port=apiprot,debug=True)
